import { getOSSToken } from '@/api/common';
import { client, newGuid } from '@/utils/alioss';
import { getExtension } from '@/utils/fileExtensions';
import { ref } from 'vue';
const UPLOAD_ERROR = `${import.meta.env.VITE_OSS_BUCKET_URL}/default/upload-error.png`;

// 上传图片到阿里云
// 图片上传后转化为链接
interface AliyunKey {
  accessKeyId: string;
  accessKeySecret: string;
  securityToken: string;
  expiration: string; // Token 的过期时间
}
let aliyunKey = ref<AliyunKey | null>(null);
const detectFileType = (fileOrBlob: File | Blob): string => {
  if (fileOrBlob instanceof File) {
    return fileOrBlob.type;
  }
  return fileOrBlob.type || 'application/octet-stream';
};

const getFileExtension = (fileOrBlob: File | Blob): string | null => {
  if (fileOrBlob instanceof File) {
    return getExtension(fileOrBlob.name);
  }
  return null; // For Blob, we might not have the extension, so we'll handle it later.
};

export const uploadImageToAliOS = async (blob: any,uploadPath: string = 'whitepeachOrder') => {
  // 检测token是否过期
  const isTokenExpired = () => {
    if (!aliyunKey.value) return true;
    const expiration = new Date(aliyunKey.value.expiration).getTime();
    const now = Date.now();
    return expiration <= now;
  };

  if (!aliyunKey.value || isTokenExpired()) {
    const data: any = await getOSSToken();
    if (data && data.code === 0 && data.data) {
      aliyunKey.value = { ...data.data, expiration: new Date(Date.now() + 300 * 1000).toISOString() };
    }
  }
  if (!aliyunKey.value) {
    return UPLOAD_ERROR;
  }

  const { accessKeyId, accessKeySecret, securityToken } = aliyunKey.value as AliyunKey;
  const fileGuid = newGuid();
  const fileSuffix = getFileExtension(blob) || 'jpg'; // Default to jpg if Blob doesn't have an extension
  const newFileName = `${uploadPath}/${fileGuid}.${fileSuffix}`;

  const contentType = detectFileType(blob);
  // console.log('上传图片到阿里云', contentType);

  try {
    const res = await client(accessKeyId, accessKeySecret, securityToken).put(newFileName, blob, {
      headers: {
        'Content-Type': contentType,
      },
      progress: (p: { percent: any }) => {
        console.log(`Upload Progress: ${p.percent}%`);
      },
    });

    if (res?.res?.statusCode === 200) {
      console.log('上传阿里云成功', res);
      const imageUrl = res.res.requestUrls[0];
      return imageUrl;
    } else {
      return UPLOAD_ERROR;
    }
  } catch (error) {
    return UPLOAD_ERROR;
  }
};
